const express = require('express');
const router = express.Router();
const PatientModel = require('../db/PatientModel');//患者模型
const SchedulingModel = require('../db/SchedulingModel');//排班模型
const UserModel = require('../db/UserModel');//用户模型
const DepartmentModel = require('../db/DepartmentModel');//科室模型
const RoleModel = require('../db/RoleModel');//角色模型
const CmmuseumModel = require('../db/CmmuseumModel');//门店 模型
const RegistrationinformationModel = require('../db/RegistrationinforMation');//挂号信息表
const Medicalinformation = require('../db/MedicalinforMation');

const moment = require('moment');
const now = () => {
    return moment().format('YYYY-MM-DD HH:mm:ss')
}
const Fun = require("../middlewares/Fun")
/**
 * 患者模块
 * 患者信息CRUD
 * 获取待分诊和已分诊信息,分页查询
 */

//添加患者信息
router.post('/save', function (req, res) {
    let dataObj = req.body;
    dataObj.createtime = now();
    let user = req.user;
    if (!dataObj.username || !dataObj.usersex || !dataObj.userbirthday) {
        return res.json({
            code: 201,
            mes: '缺少必要参数.'
        });
    }
    // if (dataObj.username) {
    //     let reg = /^[\u4e00-\u9fa5]{0,}$/;
    //     if (!reg.test(dataObj.username)) {
    //         return res.json({
    //             code: 201,
    //             mes: '姓名非法.'
    //         });
    //     }
    // }
    if (dataObj.familydata) {
        dataObj.familydata = JSON.parse(req.body.familydata)
    }
    if (dataObj.registerpeople) {
        dataObj.registrationmes = JSON.parse(req.body.registerpeople);
    }
    if (dataObj.signmes) {
        dataObj.signmes = JSON.parse(req.body.signmes)
    }
    if (dataObj.seedoctormes) {
        dataObj.seedoctormes = JSON.parse(req.body.seedoctormes)
    }
    let cs = new PatientModel(dataObj);
    cs.save().then(docs => {
        // let obj = dataObj.registrationmes[0];
        // obj.payer = docs._id;
        // obj.doctor = { id: user._id, name: user.name };
        // obj.receptiontime = now();
        // Fun.registration(obj);
        return res.json({
            code: 200,
            mes: '添加成功.',
            data: docs
        });
    }).catch(err => {
        return res.json({
            code: 201,
            mes: "数据库繁忙,请稍后重试.",
            error: err
        });
    });
});

//修改
router.post('/update', function (req, res) {
    const _id = req.body.id;
    const temp = req.body;
    if (temp.familydata) {
        temp.familydata = JSON.parse(req.body.familydata)
    }
    if (temp.registrationmes) {
        temp.registrationmes = JSON.parse(req.body.registrationmes)
    }
    if (temp.signmes) {
        temp.signmes = JSON.parse(req.body.signmes)
    }
    if (temp.seedoctormes) {
        temp.seedoctormes = JSON.parse(req.body.seedoctormes)
    }
    if (!_id) {
        return res.json({
            code: 201,
            mes: "缺少参数!"
        })
    }
    PatientModel.findById(_id).then(user => {
        if (user) {
            return PatientModel.update({ _id }, { $set: temp }).then(docs => {
                return res.json({
                    code: 200,
                    mes: '修改成功.'
                });
            }).catch(err => {
                return res.json({
                    code: 201,
                    mes: '修改失败.'
                });
            })
        } else {
            return res.json({
                code: 202,
                mes: '此ID不存在.'
            });
        }
    }).catch(err => {
        return res.json({
            code: 203,
            mes: '数据库错误,请稍后重试.'
        });
    })
});

//修改医生分诊信息
router.post('/modification', function (req, res) {
    const _id = req.body.id;
    const temp = req.body;
    let user = req.user;
    let obj;
    if (temp.registrationmes) {
        temp.registrationmes = JSON.parse((req.body.registrationmes).slice(1, -1))
        obj = temp.registrationmes;
    }
    if (!_id || !obj.receptiontime || !obj.section.id || !obj.paystate || !obj.registrationmoney || !obj.registrationlv) {
        return res.json({
            code: 201,
            mes: "缺少参数!"
        })
    }
    let pares = {
        "registrationmes.0.receptiontime": temp.registrationmes.receptiontime,
        // "registrationmes.0.receptionstate": temp.registrationmes.receptionstate,
        "registrationmes.0.receptiontype": temp.registrationmes.receptiontype,
        "registrationmes.0.section": temp.registrationmes.section,
        "registrationmes.0.doctor": temp.registrationmes.doctor,
        // "registrationmes.0.registerpeople": temp.registrationmes.registerpeople,
        "registrationmes.0.registrationlv": temp.registrationmes.registrationlv,
        "registrationmes.0.registrationmoney": temp.registrationmes.registrationmoney,
        "registrationmes.0.paystate": temp.registrationmes.paystate,
        "status": temp.status
    }
    PatientModel.findOne({ _id: _id }).then(result => {
        if (result) {
            return PatientModel.update({ _id: _id }, { $set: pares }).then(data => {
                temp.registrationmes.payer = _id;
                temp.registrationmes.registerpeople = { id: user._id, name: user.name }
                Fun.registration(temp.registrationmes);
                return res.json({
                    data,
                    code: 200,
                    mes: '修改成功。'
                });
            })
        } else {
            return res.json({
                result,
                code: 201,
                mes: '修改失败。'
            });
        }
    }).catch(err => {
        return res.json({
            err,
            code: 201,
            mes: '发生意外错误。'
        });
    })
});

//删除
router.post('/delete', function (req, res) {
    const _id = req.query.id;
    if (!_id) {
        return res.json({
            code: 201,
            mes: "缺少参数!"
        });
    }
    PatientModel.findOne({ _id }).then(data => {
        if (data) {
            return data.remove().then(data => {
                return res.json({
                    code: 200,
                    mes: "删除成功."
                });
            })
        } else {
            return res.json({
                code: 201,
                mes: "删除失败."
            });
        }
    }).catch(err => {
        return res.json({
            code: 201,
            mes: "数据库错误,请稍后重试.",
            error: err
        });
    })
});

//根据ID查询
router.get('/one/:id', function (req, res) {
    const _id = req.params.id;
    if (!_id) {
        return res.json({
            code: 201,
            mes: '缺少参数.'
        });
    }
    PatientModel.findOne({ _id: _id }).lean(true).then(user => {
        return Medicalinformation.find({ id: _id }).limit(1).sort({ savetime: -1 }).then(med => {
            if (user) {
                user.medica = med;
                return res.json({
                    code: 200,
                    mes: '查询成功.',
                    data: user
                });
            } else {
                return res.json({
                    code: 201,
                    mes: '查询失败,请检查id.'
                });
            }
        })
    }).catch(err => {
        return res.json({
            code: 201,
            mes: '查询失败.',
        });
    })
});

//获取待分诊和已分诊信息,分页查询
router.post('/list', function (req, res) {
    const searchtext = req.body.searchtext;
    const starttime = req.body.starttime;
    const endtime = req.body.endtime;
    let status = req.body.status;
    let pageindex = req.body.pageindex || 1;//页码
    let pagesize = req.body.pagesize || 12;//每页显示数据条数  createtime: { $gte: starttime }, createtime: { $lte: endtime } 
    let query = {};
    let or = [];

    if (starttime || endtime) {
        query.createtime = { $gte: starttime + " 00:00:00", $lte: endtime + " 24:00:00" }
        //query.$or = or;
    };
    if (searchtext) {
        let reg = /^[0-9]+.?[0-9]*$/;
        let regs = new RegExp(searchtext)
        if (reg.test(searchtext)) {
            or.push({ userphone: { $regex: regs } })
        } else {
            or.push({ username: { $regex: regs } })
        }
        query.$or = or
    }
    if (status) {
        query.status = status;
    }
    if (status == 1) {//待分诊列表
        PatientModel.count(query).then(counts => {
            return PatientModel.find(query).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).lean(true).then(patient => {
                for (let i = 0; i < patient.length; i++) {
                    patient[i].Receptionmes = patient[i].registrationmes;
                    patient[i].registrationmes = '';
                }
                return res.json({
                    code: 200,
                    mes: '查询成功.',
                    counts,
                    data: patient
                });
            })
        }).catch(err => {
            return res.json({
                code: 201,
                mes: '查询失败.',
                data: err
            });
        })
    } else {//已分诊列表
        PatientModel.count(query).then(counts => {
            return PatientModel.find(query).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).lean(true).then(patient => {
                let objarr = {};
                let idarr = [];
                for (let i = 0; i < patient.length; i++) {
                    idarr.push(patient[i]._id.toString());
                }
                return RegistrationinformationModel.find({ payer: { $in: idarr } }).lean(true).then(registrationinfor => {
                    for (let i = 0; i < registrationinfor.length; i++) {
                        objarr[registrationinfor[i].payer] = registrationinfor[i];
                    }
                    for (let i = 0; i < patient.length; i++) {
                        patient[i].Receptionmes = patient[i].registrationmes;
                        patient[i].registrationmes = objarr[patient[i]._id.toString()];//每个患者的对应挂号信息
                    }
                    return res.json({
                        code: 200,
                        mes: '查询成功.',
                        counts,
                        data: patient
                    });
                })
            })
        }).catch(err => {
            return res.json({
                code: 201,
                mes: '查询失败.',
                data: err
            });
        })
    }

});

//分诊获取医生列表
router.post('/doctorlist', function (req, res) {
    const time = req.body.time;
    const department = req.body.department;//科室
    const optionname = req.body.optionname;
    const textname = req.body.name;

    if (textname != "") {
        UserModel.find({ name: textname }, { name, department, totreat, alreadyaccepts }).then(user => {
            return res.json({
                code: 200,
                mes: '查询成功.',
                data: user
            });
        }).catch(err => {
            return res.json({
                code: 201,
                mes: '查询错误.'
            });
        })
    } else if (department != "") {
        UserModel.find({ department: DepartmentModel }, { name, department, totreat, alreadyaccepts }).then(user => {
            return res.json({
                code: 200,
                mes: '查询成功.',
                data: user
            });
        }).catch(err => {
            return res.json({
                code: 201,
                mes: '查询错误.'
            });
        })
    } else if (department != "" && optionname != "") {
        UserModel.find({ department: DepartmentModel, name: optionname }, { name, department, totreat, alreadyaccepts }).then(user => {
            return res.json({
                code: 200,
                mes: '查询成功.',
                data: user
            });
        }).catch(err => {
            return res.json({
                code: 201,
                mes: '查询错误.'
            });
        })
    } else {
        UserModel.find({ name, department, totreat, alreadyaccepts }).then(user => {
            return res.json({
                code: 200,
                mes: '查询成功.',
                data: user
            });
        }).catch(err => {
            return res.json({
                code: 201,
                mes: '查询错误.'
            });
        })
    }
});

//完成登记并分诊医生列表
router.get('/patient', function (req, res) {
    let doctorname = req.body;
    let scopetime = req.body;
    let query = {};
    UserModel.find({}, { password: 0 }).then(data => {
        return Promise.all(data.map(value => {
            let querys;
            return RoleModel.find({ _id: value.role }, ['name']).then(roles => {
                value._doc.role = roles[0].name
                return value
            })
        }))

    }).then(data2 => {
        res.json({
            data2
        })
    }).catch(err => {
        return res.json({ code: 201, mes: "数据库繁忙,请稍后重试.", data: err });
    })
    // let departments = [];
    // let users = [];
    // UserModel.find().then((data) => {
    //     users = data;
    //     let p1 = DepartmentModel.find({}, ['name']); department: [String],//关联科室
    //     let p2 = RoleModel.find({}, ['name']);
    //     let p3 = CmmuseumModel.find({}, ['name']);
    //     return Promise.all([p1, p2, p3]);
    //     // 科室多个 ，门店多个 ，角色一个     
    // }).then((data) => {   // data[o] department data[1] role data[2] Cmmuseum
    //     console.log(data)
    //     const cacheObj = {};

    //     for (let i = 0; i < data[0].length; i++) {
    //         cacheObj[data[0][i]._id] = data[0][i];
    //     }
    //     for (let i = 0; i < data[1].length; i++) {
    //         cacheObj[data[1][i]._id] = data[1][i];
    //     }
    //     for (let i = 0; i < data[2].length; i++) {
    //         cacheObj[data[2][i]._id] = data[2][i];
    //     }

    //     for (let i = 0; i < users.length; i++) {
    //         for (let j = 0; j < users[i].department.length; j++) {
    //             users[i].department[j] = cacheObj[users[i].department[j]]
    //         }
    //         users[i].role = cacheObj[users[i].role].name;

    //         for (let j = 0; j < users[i].shop.length; j++) {
    //             users[i].shop[j] = cacheObj[users[i].shop[j]]
    //         }
    //     }
    //     return res.json({ code: 200, users });
    // }).catch((err) => {
    //     return res.json({ code: 201, mes: "数据库繁忙,请稍后重试.", data: err });
    // })
});


module.exports = router;
